//
//  WmcWatermarkSelectVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/4.
//

import RxRelay
import UIKit
import YPBedrock
import YPNetwork

class WmcWatermarkSelectVM: WmcBaseVM {
    /// 水印分类列表
    let watermarkClassifyListRelay: BehaviorRelay<[WmcWatermarkClassifyModel]> = .init(value: [])

    /// 当前显示的水印列表
    let currentWatermarkListRelay: BehaviorRelay<[WmcWatermarkDetailModel]> = .init(value: [])

    /// 上一次使用的分类
    var beforeClassify: WmcWatermarkClassifyModel?

    /// 加载水印列表
    func loadWatermarkList() {
//        let watermarkGroupType = YPWmcManager.shared.watermarkGroupType
//        WmcWatermarkListDBManager.searchClassifyList(templateGroupKey: watermarkGroupType.info.key) { [weak self] list in
//            guard let weakSelf = self else { return }
//            if !list.isEmpty {
//                weakSelf.loadList(list)
//            }
            let watermarkGroupType = YPWmcManager.shared.watermarkGroupType
            WmcMediaWatermarkAPI.fetchWatermarkList(watermarkIds: watermarkGroupType.info.templateIds, success: { [weak self] list in
                guard let weakSelf = self else { return }
                weakSelf.loadList(list)
                // 缓存
//                WmcWatermarkListDBManager.insertClassifyList(templateGroupId: watermarkGroupType.info.key, classifyList: list)
            }) { err in

            }
//        }
    }

    /// 加载列表
    func loadList(_ list: [WmcWatermarkClassifyModel]) {
        watermarkClassifyListRelay.accept(list)
        // 设置上一次使用分类
        if let beforeClassify = beforeClassify {
            currentWatermarkListRelay.accept(beforeClassify.watermarks)
        } else if let first = list.first {
            beforeClassify = first
            currentWatermarkListRelay.accept(first.watermarks)
        }
    }

    /// 切换分类
    func switchClassify(_ classify: WmcWatermarkClassifyModel) {
        // 寻找该分类列表
        watermarkClassifyListRelay.value.forEach { _classify in
            if _classify.classifyId == classify.classifyId {
                beforeClassify = _classify
                // 发出信号
                currentWatermarkListRelay.accept(_classify.watermarks)
            }
        }
    }
}
